package middleware

import (
	//"fmt"
	"gitee.com/banyanhouse/distill-infra/web"
	"gitee.com/banyanhouse/distill-micro-grpc-hystrix/micro-gateway/Services"
	"gitee.com/banyanhouse/distill-micro-grpc-hystrix/micro-gateway/apis/wrappers"
	"gitee.com/banyanhouse/distill-micro-grpc-hystrix/micro-gateway/utils"
	"github.com/kataras/iris/context"
	"github.com/micro/go-micro/v2"
	"net/http"

	//"runtime"
)

func ProdMiddleware(ctx context.Context) {

	// 开启一个go-micro服务调用客户端
	myService := micro.NewService(
		micro.Name("prod.client"),
		micro.WrapClient(wrappers.NewLogWrapper),
		micro.WrapClient(wrappers.NewProdsWrapper),
	)
	// 声明注册中心micro_prod_server服务
	prodService := Services.NewProdService(
		"micro_prod_server",
		myService.Client(),
	)
	ctx.Values().Save("prodService", prodService, false)
	ctx.Next()
}

// 统一异常处理middleware
func ErrorMiddleware(ctx context.Context) {
	defer func() {
		if err := recover(); err != nil {
			if ctx.IsStopped() {
				return
			}
			//var stacktrace string
			res := &web.Res{}
			//for i := 1; ; i++ {
			//	_, f, l, got := runtime.Caller(i)
			//	if !got {
			//		break
			//	}
			//	stacktrace += fmt.Sprintf("%s:%d\n", f, l)
			//}

			//errMsg := fmt.Sprintf("错误信息: %s", err)
			//// when stack finishes
			//logMessage := fmt.Sprintf("从错误中回复：('%s')\n", ctx.HandlerName())
			//logMessage += errMsg + "\n"
			//logMessage += fmt.Sprintf("\n%s", stacktrace)
			//// 打印错误日志
			//ctx.Application().Logger().Warn(logMessage)
			// 返回错误信息
			utils.ErrRes(err.(error), nil, res)
			ctx.StatusCode(http.StatusInternalServerError)
			ctx.JSON(res)
			ctx.StopExecution()
		}
	}()
	ctx.Next()
}
